package com.example.demo.common.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: ak
 * @Date: 2020/4/1 0:16
 */
@Slf4j
@ControllerAdvice
public class CustomHandler{
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public String handlerException(CustomException e, HttpServletRequest request) {
        log.error("发生自定义异常！原因是{}:",e.getMsg());
        request.setAttribute("javax.servlet.error.status_code", e.getCode());
        putErrorMsg(request,e.getCode(),e.getMsg());
        return e.getMsg();
    }
    @ExceptionHandler(value =NullPointerException.class)
    public String exceptionHandler(HttpServletRequest request, NullPointerException e){
        log.error("发生空指针异常！原因是:",e);
        request.setAttribute("javax.servlet.error.status_code",500);
        putErrorMsg(request,null,e.getMessage());
        return "forward:/error/4xx";
    }
    @ExceptionHandler(value =Exception.class)
    public String exceptionHandler(HttpServletRequest request, Exception e){
        log.error("未知异常！原因是:",e);
        request.setAttribute("javax.servlet.error.status_code",500);
        putErrorMsg(request,null,e.getMessage());
        return "forward:/error/4xx";
    }

    private void putErrorMsg(HttpServletRequest request,Integer code,String msg){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createDate = sdf.format(date);
        request.setAttribute("time",createDate);
        request.setAttribute("code",code);
        request.setAttribute("msg",msg);
        if (code==null){
            request.setAttribute("code",500);
        }
        if (msg==null){
            request.setAttribute("msg","未知异常");
        }
    }
}
